
#include <iostream>
#include <unistd.h>
#include <cerrno>
#include <cstring>
#include <string>
#include <sys/wait.h>
#include <sys/types.h>

const int SIZE = 1024;


std::string GetOtherMsg()
{
    static int cnt = 0;
    std::string msg_id = std::to_string(cnt);
    cnt++;
    pid_t self_id = getpid();
    std::string str_pid = std::to_string(self_id);

    std::string msg = "msg_id: ";
    msg += msg_id;
    msg += ", my pid: ";
    msg += str_pid;

    return msg;
}

// 子进程写入
void SubProcessWrite(int wfd)
{
    int pipesize = 0;
    std::string msg = "This is child process! ";
    char c = 'a';
    while (true)
    {
        // // 子进程发给父进程的消息
        // std::string info = msg + GetOtherMsg();
        // // 复用文件接口
        // write(wfd, info.c_str(), info.size());
        // sleep(1);


        // sleep(1000);
        write(wfd, &c, sizeof(c));
        std::cout << "pipesize: " << ++pipesize << ", c: " << c << std::endl;
        if (++c == 'g') break;
        // break;
        sleep(1);
    }
}

// 父进程读取
void ParentProcessRead(int rfd)
{
    char inbuffer[SIZE];
    while (true)
    {
        // sleep(1000);
        ssize_t n = read(rfd, inbuffer, sizeof(inbuffer) -1);
        if (n > 0)
        {
            inbuffer[n] = '\0';
            std::cout << "father get message: " << inbuffer << std::endl;
        }
        else if (n == 0)
        {
            std::cout << "client quit, parent get return val: " << n << ",  parent quit too" << std::endl;
            break;
        }
        else
        {
            std::cerr << "read error" << std::endl;
            break;
        }
    }
}

int main()
{
    // 1、创建管道

    int pipefd[2];
    // 输出型参数：rfd, wfd
    int n = pipe(pipefd);
    if (n != 0)
    {
        std::cerr << "errno: " << errno << ", errstring: " << strerror(errno) << std::endl;
        return 1;
    }
    // pipefd[0] -> rfd
    // pipefd[1] -> wfd
    std::cout << "pipefd[0]: " << pipefd[0] << ", pipefd[1]: " << pipefd[1] << std::endl;

    // 2、创建子进程

    pid_t id = fork();
    if (id == 0)
    {
        // child ---> write
        // 3、关闭不需要的文件描述符
        close(pipefd[0]);

        // 子进程写
        SubProcessWrite(pipefd[1]);

        close(pipefd[1]);
        exit(0);
    }

    // parent ---> read
    // 3、关闭不需要的文件描述符
    close(pipefd[1]);

    // 父进程读
    ParentProcessRead(pipefd[0]);

    close(pipefd[0]);

    // 父进程等待子进程（阻塞等待），防止子进程变为僵尸进程
    pid_t rid = waitpid(id, nullptr, 0);
    if (rid > 0)
    {
        std::cout << "wait child process done" << std::endl;
    }

    return 0;
}
